<?php
/**
 * Created by Pixoid.
 * Date: 16.03.11
 * @version 1.0
 */

 class Validator {
    protected $_errors = array();
    protected $_validators = array();
    protected $_attrs= array();

    public function addValidator($field, $rule,$attr = array()){
        $this->_validators[$field][] = $rule;
        $this->_attrs[$field][] = $attr;
    }

    public function validate($hash){
        foreach($hash as $field=>$value){
            if(isset($this->_validators[$field])){

                foreach($this->_validators[$field] as $rule)
                    $this->$rule($field, $value);
            }
        }


        return empty($this->_errors);
    }

    public function email($field, $value){
        $pattern='/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/';
        $valid = is_string($value) && (preg_match($pattern,$value));
        if(!$valid){
            $this->_errors[$field][] = "Поле {$field} не является e-mail адресом.";
        }
    }

    public function length($field, $value){
        $min = isset($this->_attrs[$field]['min']) ?  $this->_attrs[$field]['min'] : 0;
        $max = isset($this->_attrs[$field]['max']) ?  $this->_attrs[$field]['max'] : 0;
        if(mb_strlen($value, 'utf-8') < $min){
            $this->_errors[$field][] = "Поле {$field} не может быть кароче {$min} символов.";
        }
        if(mb_strlen($value, 'utf-8') > $max){
           $this->_errors[$field][] = "Поле {$field} не может быть длиннее {$max} символов.";
        }
    }

    public function notNull($field, $value){
        if(empty($value)){
            $this->_errors[$field][] = "Поле {$field} не может быть пустым.";
        }
    }

    public function getErrors(){
        return $this->_errors;
    }
}
